<?php

namespace app\home\controller;

use app\common\controller\Home;

class Post extends Home
{
    public function __construct()
    {
        parent::__construct();
        $this->PostModel = model("Post.Post");
        $this->RecordModel = model('User.Record');
        $this->UserModel = model('User.User');
    }
    // 添加帖子
    public function add()
    {

        if ($this->request->isPost()) {
            /**
             * 增加消费记录-----消费记录表
             * 用户更新积分-----用户表  用户积分-（悬赏积分+帖子状态所需要的积分）
             * 帖子插入数据-----帖子表
             */

            //  开启事务
            $this->PostModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            // 验证码
            $vercode = $this->request->param('vercode');
            if (!captcha_check($vercode)) {
                $this->error('验证码错误');
            }

            // 悬赏积分
            $acceptPoint = $this->request->param('point', 0);

            // 帖子状态积分
            $state = $this->request->param('state', 0);

            // 0  1 2 3  查询相应的积分
            $StatePoint = model('Config')->where('key', "PostState{$state}")->value('value');
            // halt($StatePoint);
            $StatePoint = $StatePoint ? $StatePoint : 0;

            // 悬赏的积分 + 帖子状态所需的积分 = 发帖所需要的积分
            $PostPoint = bcadd($acceptPoint, $StatePoint);

            // 用户的积分 - 发帖所需要的积分
            $UpdatePoint = bcsub($this->LoginUser['point'], $PostPoint);
            if ($UpdatePoint < 0) {
                $this->error('积分不足，在及时充值');
            }
            // 封装更新用户积分的数据
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $UpdatePoint
            ];
            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);
            if ($UserStatus == false) {
                $this->error($this->UserModel->getError());
            }
            // 接收全部参数
            $param = $this->request->param();
            $PostData = [
                'cateid' => $param['cateid'],
                'title' => $param['title'],
                'content' => $param['content'],
                'point' => $PostPoint,
                'state' => $param['state'],
                'userid' => $this->LoginUser['id']
            ];
            // 帖子表
            $PostStatus = $this->PostModel->validate('common/Post/Post')->save($PostData);
            if ($PostStatus == false) {
                $this->UserModel->rollback();
                $this->error($this->PostModel->getError());
            }

            // 更新消费记录表
            $RecordData = [
                'point' => $PostPoint,
                'content' => "您发的帖子【{$PostData['title']}】成功，消费了{$PostPoint}积分",
                'state' => 1,
                'userid' => $this->LoginUser['id'],
            ];
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            if ($RecordStatus == false) {
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError());
            }

            if ($UserStatus == false || $PostStatus == false || $RecordStatus == false) {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error('发布失败');
            } else {
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->success('发布成功', url('home/index/index'));
            }
        }

        // 获取分类
        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();

        $StateList = $this->PostModel->state();

        return $this->fetch('', [
            'CateList' => $CateList,
            'StateList' => $StateList
        ]);
    }

    // 编辑帖子
    public function edit()
    {
        $userid = $this->request->param('userid');
        $postid = $this->request->param('postid', '');
        $postinfo = $this->PostModel->where('id', $postid)->find();

        // 获取分类
        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();
        $StateList = $this->PostModel->state();

        if (empty($CateList)) {
            $this->error('该帖子不存在');
        }
        if ($postinfo['userid'] != $this->LoginUser['id']) {
            $this->error('无权限！！！');
        }

        if ($this->request->isPost()) {
            $params = $this->request->param();

            if (!captcha_check($params['vercode'])) {
                $this->error('验证码错误');
            }
            
            // 封装数据
            $data = [
                'id' => $postid,
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content']
            ];
            $res = $this->PostModel->isUpdate(true)->save($data);
            if ($res == false) {
                $this->error('编辑失败');
            } else {
                $this->success('编辑成功', url('home/index/info', ['postid' => $postid]), null, 1);
            }
        }

        return $this->fetch('', [
            'CateList' => $CateList,
            'StateList' => $StateList,
            'postinfo' => $postinfo
        ]);
    }

    // 删除帖子
    public function del() {
        if ($this->request->isPost()) {
            $postid = $this->request->param('id');

            $post = $this->PostModel->find($postid);
            if (!$post) {
                $this->error('该帖子已不存在，无法删除');
            }

            // 删除
            $res = $this->PostModel->destroy($postid);
            // $res = $post->delete();
            if ($res == false) {
                $this->error('删除失败');
            }
            $this->success('删除成功', url('home/index/index'));
        }
    }
}
